package com.hx.factory.cglibproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理
 */
public class CglibProxyFactory {
    private Object target;

    public CglibProxyFactory(Object target){
        this.target = target;
    }

    public Object getProxy(){
        /**
         *
         */
       return Enhancer.create(target.getClass(),
                new MethodInterceptor() {
                    /**
                     *
                     * @param proxy  代理对象
                     * @param method  目标方法对象
                     * @param args   目标方法参数
                     * @param methodProxy  代理方法对象
                     * @return
                     * @throws Throwable
                     */
                    @Override
                    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                        Object result = null;
                        try {
                            if(method.getName() != null && method.getName().startsWith("find")) {
                                result = method.invoke(target, args);
                            } else {
                                System.out.println("开启事务----------------");
                                //调用目标方法
                                result = method.invoke(target, args);
                                System.out.println("提交事务----------------");
                            }
                        } catch (Exception e) {
                            //e.printStackTrace();
                            System.out.println("回滚事务----------------");
                        }
                        return result;
                    }
                });


    }
}
